/*
 * Copyright (C), 2002-2015, 你的兔宝宝电子商务有限公司
 * FileName: Json2mapFactoryBean.java
 * Author:   你的兔宝宝
 * Date:     2015-7-29 上午10:34:23
 * Description: json转map的factoryBean//模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.baby.demo.utils.factory;

import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.core.io.Resource;

import com.baby.demo.utils.Jsons;
import com.baby.demo.utils.Strings;

/**
 * json转map的factoryBean<br> 
 * 〈功能详细描述〉
 *
 * @author 你的兔宝宝
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class Json2mapFactoryBean extends AbstractFactoryBean<Map<String,Object>>{
    
    private static final Logger logger = LoggerFactory.getLogger(Json2mapFactoryBean.class);

    
    /**
     * json字符串，高优先级
     */
    private String json;
    
    /**
     * 路径地址，和json二选一
     */
    private Resource location;
    
    /**
     * 读取文件编码
     */
    private String encoding;
    
    private static final String ENCODING = "UTF-8";
    
    @SuppressWarnings("rawtypes")
    @Override
    public Class<Map> getObjectType() {
        return Map.class;
    }

    @Override
    protected Map<String, Object> createInstance() throws Exception {
        return load();
    }
    
    protected Map<String, Object> load() throws Exception {
        Map<String, Object> map = null;
        try{
            if( !Strings.isEmpty(json) ){
                //NOOP
            }else if( location != null ){
                json = IOUtils.toString(location.getInputStream(),Strings.show(encoding,ENCODING));
            }else{
                logger.error("参数为空");
            }
            map = Jsons.json2map(json);
        }catch(Exception e){
            logger.error("json2map error",e);
        }
        return map;
    }
    
    
    /**
     * @return the json
     */
    public String getJson() {
        return json;
    }

    /**
     * @param json the json to set
     */
    public void setJson(String json) {
        this.json = json;
    }

    /**
     * @return the location
     */
    public Resource getLocation() {
        return location;
    }

    /**
     * @param location the location to set
     */
    public void setLocation(Resource location) {
        this.location = location;
    }

    /**
     * @return the encoding
     */
    public String getEncoding() {
        return encoding;
    }

    /**
     * @param encoding the encoding to set
     */
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

}
